package com.imooc.bilibili.handler;


import com.imooc.bilibili.domain.JsonResponse;
import com.imooc.bilibili.exception.ConditionException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) // 表示全局异常处理器优先级是最高的
public class CommonGlobalExceptionHandler {

    /**
     * @param request
     * @param e
     * @return
     * @ExceptionHandler(value = Exception.class)：表示这是一个异常处理器，Exception.class表示捕获Exception类型的错误
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody // 将java对象转换为json格式的数据
    public JsonResponse<String> commonExceptionHandler(HttpServletRequest request, Exception e) {
        // 错误信息
        String errorMsg = e.getMessage();
        if (e instanceof ConditionException) {
            String errorCode = ((ConditionException) e).getCode();
            return new JsonResponse<>(errorCode, errorMsg);
        } else {
            return new JsonResponse<>("500", errorMsg);
        }
    }
}
